package org.lt.cj.core.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lt.cj.config.entities.ConfigModel;
import org.lt.cj.core.TaskManager;
import org.lt.cj.core.server.entity.RequestTask;
import org.lt.cj.core.utils.CommandList;

/*
 * @author luohong
 * 接收任务端口4001
 * 监听命令端口4000
 */
public class TaskListener {

    private boolean shouldStop;                                                 //这个端口用来监听
    private static TaskListener listener = new TaskListener();                  //提供自身的实例

    private TaskListener() {
    }

    public static TaskListener getInstance() {

        if (listener == null) {
            listener = new TaskListener();
        }
        return listener;
    }

    class ListeningTask extends Thread {

        @Override
        public void run() {
            listeningForTask();
        }

        public void listeningForTask() {
            try {
                //接收任务端口
                ServerSocket serverSocket = new ServerSocket(4001);

                while (!shouldStop) {
                    System.out.println("Server Waiting");
                    Socket client = serverSocket.accept();
                    ObjectInputStream objectInputStream = new ObjectInputStream(client.getInputStream());
                    try {
                        RequestTask task = (RequestTask) objectInputStream.readObject();
                        String username = task.getUsername();
                        String password = task.getPassword();
                        if (username.trim().equals("boling") && password.trim().equals("%$#ltoop123")) {
                            ConfigModel configModel = task.getConfigModel();
                            TaskManager manager = TaskManager.getInstance();
                            manager.acceptNewTask(configModel);
                        }
                    } catch (ClassNotFoundException ex) {
                    } finally {
                        objectInputStream.close();
                    }
                }
            } catch (IOException ex) {
                Logger.getLogger(TaskListener.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    class ListeningCommand extends Thread {

        @Override
        public void run() {
            listeningForCommand();
        }

        public void listeningForCommand() {
            boolean runFlag = true;
            try {
                /*监听命令端口*/
                ServerSocket serverSocket = new ServerSocket(4000);
                while (runFlag) {

                    Socket client = serverSocket.accept();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
                    boolean flag = true;
                    while (flag) {

                        String s = reader.readLine();
                        if (s.trim().equals(CommandList.stopAllCommand)) {
                            TaskManager manager = TaskManager.getInstance();
                            manager.sendCommand(s.trim(), "");
                        } else if (s.indexOf(CommandList.stopCommand) != -1) {
                            String taskname = s.substring(s.indexOf(CommandList.stopCommand) + CommandList.stopCommand.length()).trim();
                            System.out.println(taskname);
                            TaskManager manager = TaskManager.getInstance();
                            manager.sendCommand(CommandList.stopCommand, taskname.trim());
                        } else if (s.trim().indexOf("quit") != -1) {
                            String responseMsg = " System Message: you have disconnect with the remote server";
                            writer.write(responseMsg);
                            writer.flush();
                            writer.close();
                            client.close();
                            break;
                        } else if (s.trim().equals(CommandList.shutApplicationCommand)) {
                            System.exit(0);
                        } else {
                            writer.write("command " + s + " invalid\n\r");
                            writer.flush();
                        }
                    }
                }
            } catch (IOException ex) {
                Logger.getLogger(TaskListener.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void startListening() {
        ListeningCommand lc = new ListeningCommand();
        Thread tc = new Thread(lc);
        tc.start();

        ListeningTask lt = new ListeningTask();
        Thread tt = new Thread(lt);
        tt.start();

        TaskManager manager2 = TaskManager.getInstance();
        manager2.reloadTasks();
    }

    public static void main(String[] args) {

        TaskListener tempListener = TaskListener.getInstance();
        tempListener.startListening();
    }
}
